package com.haha.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

public class exchange extends AppCompatActivity implements Runnable{
//一个intent只能传一个bundle，bundle的put、get都有类型设置
//data和first是同一个数据
    private static final String TAG = "hh";
    private float dollarRate=0.1f;
    private float euroRate=0.2f;
    private float wonRate=0.3f;

    TextView show;
    EditText rmb;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.week4exchange);
        show = findViewById(R.id.show);
        rmb=findViewById(R.id.inputrmb);

        //读取保存到数据
        SharedPreferences sp = getSharedPreferences("myrate",Activity.MODE_PRIVATE);
        dollarRate = sp.getFloat("dollar_rate",0.1f);
        euroRate = sp.getFloat("euro_rate",0.1f);
        wonRate = sp.getFloat("won_rate",0.1f);
        Log.i(TAG, "onCreate: get from sp dollar" + dollarRate);
        Log.i(TAG, "onCreate: get from sp euro" + euroRate);
        Log.i(TAG, "onCreate: get from sp won" + wonRate);

        handler = new Handler(){
            //对类方法的重写
            @Override
            public void handleMessage(@NonNull Message msg) {
                Log.i(TAG, "handleMessage: 收到消息");
                if (msg.what==6){
//                    String str = (String) msg.obj;
//                    Log.i(TAG, "handleMessage: str = " + str);
//                    show.setText(str);
                    float flag1= sp.getFloat("flag",0);
                    SharedPreferences.Editor editor1 = sp.edit();
                    //对比更新时间
                    Date date=new Date();
                    Calendar calendar=Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.DAY_OF_MONTH,1);
                    calendar.set(calendar.HOUR_OF_DAY,0);
                    calendar.set(calendar.MINUTE,0);
                    calendar.set(calendar.SECOND,0);
                    calendar.set(calendar.MILLISECOND,0);
                    int seconds= (int) ((calendar.getTime().getTime()-date.getTime())/1000);
                    if(seconds==0){
                        SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        float flag = 0;
                        editor.putFloat("flag",flag);
                    }
                    Bundle bd1 = (Bundle)msg.obj;
                    dollarRate = bd1.getFloat("r1");
                    euroRate = bd1.getFloat("r2");
                    wonRate = bd1.getFloat("r3");

                    Log.i(TAG, "handleMessage: dollarRate=" + dollarRate);
                    Log.i(TAG, "handleMessage: euroRate=" + euroRate);
                    Log.i(TAG, "handleMessage: wonRate=" + wonRate);

                    //如果flag为0，也就是说此时为当天的第一次更新时间，将获取到的汇率信息保存数据到sp
                    if(flag1==0) {
                        SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putFloat("dollar_rate", dollarRate);
                        editor.putFloat("euro_rate", euroRate);
                        editor.putFloat("won_rate", wonRate);
                        //第一次已提交，更改flag值，使之后的数据不再更新
                        float flag = 1;
                        editor.putFloat("flag",flag);
                        editor.apply();
                        Log.i(TAG, "网页汇率第一次更新save to sp ok");
                    }else {
                        Log.i(TAG, "本日汇率已更新");
                    }

                    //
                    Toast.makeText(exchange.this,"数据已更新",Toast.LENGTH_SHORT).show();
                }
                super.handleMessage(msg);
            }
        };

        //开启线程
        MyThread td = new MyThread();
        td.setHandler(handler);

        Thread t = new Thread(td);
        t.start();
    }

    public void click(View v) {
        Log.i(TAG, "click: aaaaaaaa");
        EditText edit1 = findViewById(R.id.inputrmb);
        String rmb = edit1.getText().toString();

        if(rmb!=null&&rmb.length()>0){

            Log.i(TAG, "click:rmb=" + rmb);
            float num = Float.parseFloat(rmb);
            float r = 0;

            if (v.getId()==R.id.btndollar){
                r = num * dollarRate;
            }else if (v.getId()==R.id.btneuro) {
                r = num * euroRate;
            }else{
                r = num * wonRate;
            }
            Log.i(TAG, "click:r=" + r);
            //输出到控件
            //TextView show = findViewById(R.id.show);
            show.setText(String.valueOf(r));
        }else {
            //重置输出
            show.setText(R.string.exchange);
            Toast.makeText(this,"请输入金额再计算",Toast.LENGTH_SHORT).show();
        }
    }

    public void  func(View v) {
        openConfig();
    }

    private void openConfig() {
        Intent config = new Intent(this, save.class);
        config.putExtra("dollar_rate_key", dollarRate);
        config.putExtra("euro_rate_key", euroRate);
        config.putExtra("won_rate_key", wonRate);

        Log.i(TAG, "openOne: dollarRate=" + dollarRate);
        Log.i(TAG, "openOne: euroRate=" + euroRate);
        Log.i(TAG, "openOne: wonRate=" + wonRate);

        //startActivity(config);
        startActivityForResult(config, 1);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //菜单（右上角设置）
        getMenuInflater().inflate(R.menu.rate,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.menu_set){
            Intent config=new Intent(this,save.class);
            config.putExtra("dollar_rate_key",dollarRate);
            config.putExtra("euro_rate_key",euroRate);
            config.putExtra("won_rate_key",wonRate);

            Log.i(TAG,"openOne: dollarRate="+dollarRate);
            Log.i(TAG,"openOne: euroRate="+euroRate);
            Log.i(TAG,"openOne: wonRate="+wonRate);

            //startActivity(config);
            startActivityForResult(config,1);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //传值和文件保存
        if(requestCode==1&&resultCode==2){
            Bundle bundle=data.getExtras();
            dollarRate= bundle.getFloat("key_dollar",0.1f);
            euroRate= bundle.getFloat("key_euro",0.1f);
            wonRate= bundle.getFloat("key_won",0.1f);

            Log.i(TAG,"onActivityResult: dollarRate="+dollarRate);
            Log.i(TAG,"onActivityResult: euroRate="+euroRate);
            Log.i(TAG,"onActivityResult: wonRate="+wonRate);

            //保存数据到sp
            SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putFloat("dollar_rate",dollarRate);
            editor.putFloat("euro_rate",euroRate);
            editor.putFloat("won_rate",wonRate);
            editor.apply();
            Log.i(TAG, "onActivityResult: save to sp ok");
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void run() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Bundle bundle = new Bundle();
        Log.i(TAG, "run: ....");

//      获取msg对象，用于返回主线程
//        Message msg = handler.obtainMessage();
//        msg.what = 6;
//        msg.obj = "Hello from run";
//        handler.sendMessage(msg);
//        Log.i(TAG, "run: 消息已发送");

        //获取网络数据
        URL url = null;
        try {
            //url = new URL("https://www.waihui321.com/eur-cny.html");
            //HttpURLConnection http = (HttpURLConnection) url.openConnection();
            //获得输入流,从输入流中捕获文本
            //InputStream in = http.getInputStream();
            //String html = inputStream2String(in);
            //Log.i(TAG, "run: html=" + html);

            Document doc = Jsoup.connect("http://www.usd-cny.com/bankofchina.htm").get();
            Log.i(TAG, "run: title=" + doc.title());

//            Elements h4s = doc.getElementsByTag("h4");
//            for (Element h4 : h4s){
//                Log.i(TAG, "run: h4=" + h4.text());
//            }

            Elements tables = doc.getElementsByTag("table");
            Element table1 = tables.first();

//            Elements hrefs = table1.getElementsByTag("a");
//            for (Element a : hrefs){
//                Log.i(TAG, "run: a=" + a.text());
//            }

            Elements trs = table1.getElementsByTag("tr");
            trs.remove(0);
            for (Element tr : trs){
                Elements tds = tr.getElementsByTag("td");
                String cname = tds.get(0).text();
                String cval = tds.get(5).text();
                //Log.i(TAG, "run: cname=" + cname + "-->" + cval);

                if ("美元".equals(cname)){
                    bundle.putFloat("r1",100f/Float.parseFloat(cval));
                }else if ("欧元".equals(cname)){
                    bundle.putFloat("r2",100f/Float.parseFloat(cval));
                }else if ("韩元".equals(cname)){
                    bundle.putFloat("r3",100f/Float.parseFloat(cval));
                }
                Log.i(TAG, "run: tr=" + tr);

            }



        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

//      获取msg对象，用于返回主线程
        Message msg = handler.obtainMessage(6,bundle);
        handler.sendMessage(msg);
        Log.i(TAG, "run: ");


    }

    private String inputStream2String(InputStream inputStream) throws IOException {
        //输入流转化成字符串输出
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream,"UTF-8");
        while (true){
            int rsz = in.read(buffer,0,buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
        return out.toString();
    }
}